package cn.mengflu.zuul.filter;

import cn.mengflu.zuul.util.FilterUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;

/**
 * @author Mengfly
 * @date 2021/3/17 22:40
 */
@Slf4j
public class GlobalErrorFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterUtils.ERROR_FILTER_TYPE;
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        final Throwable throwable = context.getThrowable();
        log.error("[ErrorFilter] errorMsg:{}", throwable.getCause().getMessage());
        context.set("error.status_code", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        context.set("error.exception", throwable.getCause());
        return null;
    }
}
